Contents

  1. Imports
  2. Defining the Data Directory and Result Directory
  3. Extracting Center Information
    1. Initializing the Classes
    2. Determining the Region of Interest
    3. Reiniatilizing the Classes
    4. Setting the Reference Image
    5. Extracting Center Related Information
    6. Some Preliminary Analysis
      1. None Values
      2. Sample Images
  4. Extracting Informations From DataFrame
    1. Frame Informations
      1. Information About DataFrame
      2. Information about Frames Numbers
        1. Getting Numerical Frame Number
      3. Creating New Columns
        1. The Region and Time
        2. The Speeds
        3. Angle
      4. Extracting Values
        1. Height
        2. Angles
        3. Speeds
  5. Fitting Curves
    1. The Curves to be Fitted
    2. Region III
      1. Data For Region III
      2. Fitting the Curves In Region III
      3. Caparing Results For Region III
      4. Calculating Informations From Parameters In Region III
        1. The Speeds In Region III
        2. The Angle In Region III
      5. Visualizating Results In Region III
        1. x and y Coordinates In Region III
        2. Speeds In Region III
        3. Angle In Region III
      6. Getting The Required Informations In Region III
      7. Adding the Information for Region III to DataFrame
    3. Region I
      1. Data For Region I
      2. Fitting the Curves
      3. Caparing Results
      4. Calculating Informations From Parameters
        1. The Speeds
        2. The Angle
      5. Visualizating Results
        1. x and y Coordinates
        2. Speeds
        3. Angle
      6. Getting The Required Informations
  6. Adding the Additional Information
    1. Saving Informations to DataFrame
    2. The Text Information
      1. Creating the Text
      2. Save the DataFrames

Imports¶

In [ ]:
from extract_center import CenterExtracter
from run import Run
from misc_tools import Plotter, Smoother
from functools import partial
import re
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
from scipy.optimize import curve_fit
import warnings

warnings.filterwarnings("ignore")
plt.rcdefaults()
matplotlib.rcParams["figure.figsize"] = (8, 6)

Defining the Data Directory and Result Directory¶

In [ ]:
sequence = "ref"
DATA_DIR = "../../data/extracted_images/" + sequence
RESULT_DIR = "../../data/results/" + sequence

Extracting Center Information¶

Initializing the Classes¶

In [ ]:
run = Run(DATA_DIR, RESULT_DIR)
ce = CenterExtracter()

Determining the Region of Interest¶

In [ ]:
images = run.get_images()
img_1 = ce._read_image(images[0])
ce._show_image(img_1)
In [ ]:
region_of_interset = (850, 350, 950, 450)

Reiniatilizing the Classes¶

In [ ]:
run = Run(DATA_DIR, RESULT_DIR, region=region_of_interset)

Setting the Reference Image¶

In [ ]:
run._set_ref_image(-10)

Extracting Center Related Information¶

In [ ]:
df = run.all_points(
    crop_included=True, binary=True, verbose=False, num_images=None, raise_error=False, file_name="dynamic_ap.csv",
)
Getting list of images...
Extracting data from images...
Extracting data from images: 100%|██████████| 171/171 [00:06<00:00, 25.70it/s]
Saving to csv...
Done!

Some Preliminary Analysis¶

None Values¶

In [ ]:
df.isna().sum()
Out[ ]:
id       0
x        3
y        3
r1       3
r2       3
theta    3
dtype: int64
In [ ]:
none_values = df.isna().sum()["x"]
total_frames = len(df)
unrealistic = len(
    df[((df["r1"] + df["r2"]) / 2 > 20) | ((df["r1"] + df["r2"]) / 2 < 5)]
)
In [ ]:
none_values, unrealistic
Out[ ]:
(3, 3)
In [ ]:
df = pd.read_csv(RESULT_DIR + "/dynamic_ap.csv")

Sample Images¶

In [ ]:
p = Plotter(df, RESULT_DIR)
p.get_samples(25, file_name=f"{sequence}_samples.png")

Extracting Informations From DataFrame¶

Frame Informations¶

Information About DataFrame¶

In [ ]:
df = pd.read_csv(RESULT_DIR + "/dynamic_ap.csv")
In [ ]:
none_frames = df.isna().sum()["x"]
total_frames = len(df)
unrealistic = len(
    df[((df["r1"] + df["r2"]) / 2 > 20) | ((df["r1"] + df["r2"]) / 2 < 5)]
)

Information about Frames Numbers¶

In [ ]:
info_dict = {
    "first_frame": 1,
    "last_frame": 2,
    "contact_frame": 3,
    "leave_frame": 4,
    "angle": 5,
    "passthrough": 6,
}
In [ ]:
def get_info(file):
    information = {}
    with open(file, "r") as f:
        texts = f.readlines()
    for key, value in info_dict.items():
        line = texts[value]
        info = line.split(":")[1].strip()
        information[key] = info
    return information


information = get_info(f"{DATA_DIR}.txt")
In [ ]:
first_frame = DATA_DIR + "/" + information["first_frame"]
last_frame = DATA_DIR + "/" + information["last_frame"]
contact_frame = DATA_DIR + "/" + information["contact_frame"]
angle = information["angle"]
leave_frame = DATA_DIR + "/" + information["leave_frame"]
passthrough = information["passthrough"]

Getting Numerical Frame Number¶

In [ ]:
reg = re.compile(r"\d{3}")
first_frame_num = int(reg.findall(first_frame)[0])
contact_frame_num = int(reg.findall(contact_frame)[0])
leave_frame_num = int(reg.findall(leave_frame)[0])
last_frame_num = int(reg.findall(last_frame)[0])
first_frame_num, contact_frame_num, leave_frame_num, last_frame_num
Out[ ]:
(17, 68, 107, 161)
In [ ]:
df = df.loc[:last_frame_num]

Creating New Columns¶

The Region and Time¶

In [ ]:
s = Smoother(df)
df_s = s.smoothen(remove_noise=False)
df_c = df[df["x"].notna()]
In [ ]:
def get_region(id):
    id = id.split("/")[-1].split(".")[0]
    id = int(id)
    if id<=first_frame_num:
        return "O"
    elif id>=first_frame_num and id<=contact_frame_num:
        return "I"
    elif id>=contact_frame_num and id<=leave_frame_num:
        return "II"
    else:
        return "III"
In [ ]:
df_c["Region"] = df_c["id"].apply(get_region)
df_s["Region"] = df_s["id"].apply(get_region)
In [ ]:
def get_time(id):
    id = id.split("/")[-1].split(".")[0]
    id = int(id)
    return id
In [ ]:
df_c["time"] = df_c["id"].apply(get_time)
df_s["time"] = df_s["id"].apply(get_time)

The Speeds¶

In [ ]:
df_s["vx"] = df_s["x"].diff(7) / 7
df_s["vy"] = df_s["y"].diff(7) / 7
df_s.dropna(inplace=True)
df_s["vx"] = df_s["vx"].astype(float)
df_s["vy"] = df_s["vy"].astype(float)
df_s["v"] = np.sqrt(df_s["vx"] ** 2 + df_s["vy"] ** 2)

df_c["vx"] = df_c["x"].diff(7) / 7
df_c["vy"] = df_c["y"].diff(7) / 7
df_c.dropna(inplace=True)
df_c["vx"] = df_c["vx"].astype(float)
df_c["vy"] = df_c["vy"].astype(float)
df_c["v"] = np.sqrt(df_c["vx"] ** 2 + df_c["vy"] ** 2)
In [ ]:
# plt.plot(df_s["vy"], label = "smoothened")
# plt.plot(df_c["vy"], label = "raw")
# plt.legend();
In [ ]:
# plt.plot(df_s["v"], label = "smoothened")
# plt.plot(df_c["v"], label = "raw")
# plt.legend();

Angle¶

In [ ]:
def get_angle(row):
    vx = row["vx"]
    vy = -row["vy"]
    if vx == 0 and vy == 0:
        return 0
    elif vx == 0:
        return 90
    else:
        return np.arctan(vy / vx) * 180 / np.pi
In [ ]:
df_s["angle"] = df_s.apply(get_angle, axis=1)
df_c["angle"] = df_c.apply(get_angle, axis=1)
In [ ]:
# plt.plot(df_s["angle"], label = "smoothened")
# plt.plot(df_c["angle"], label = "raw")
# plt.legend();

Extracting Values¶

Height¶

In [ ]:
y0 = df_c[df_c["time"] == first_frame_num]["y"].values[0]
yc = df_c[df_c["time"] == contact_frame_num]["y"].values[0]
hc = yc - y0

y0 = df_s[df_s["time"] == first_frame_num]["y"].values[0]
ys = df_s[df_s["time"] == contact_frame_num]["y"].values[0]
hs = ys - y0
hc, hs
Out[ ]:
(161.0, 164.28606541879378)

Angles¶

In [ ]:
df_c[df_c["time"] == contact_frame_num].T
Out[ ]:
68
id ../../data/extracted_images/ref/068.jpg
x 866.0
y 571.0
r1 10.0
r2 9.0
theta 17.188734
Region I
time 68
vx -0.142857
vy 4.857143
v 4.859243
angle 88.315316
In [ ]:
df_c[df_c["time"] == leave_frame_num].T
Out[ ]:
107
id ../../data/extracted_images/ref/107.jpg
x 965.0
y 610.0
r1 11.0
r2 9.0
theta 43.544792
Region II
time 107
vx 5.428571
vy -3.142857
v 6.272714
angle 30.068583
In [ ]:
df_s[df_s["time"] == contact_frame_num].T
Out[ ]:
68
id ../../data/extracted_images/ref/068.jpg
x 865.451125
y 574.445453
r1 9.818302
r2 9.164681
theta 66.866092
r 9.220079
Region I
time 68
vx -0.064635
vy 5.278286
v 5.278682
angle 89.298417
In [ ]:
df_s[df_s["time"] == leave_frame_num].T
Out[ ]:
107
id ../../data/extracted_images/ref/107.jpg
x 962.894876
y 610.847041
r1 8.444318
r2 8.67007
theta 56.957356
r 8.319342
Region II
time 107
vx 4.736515
vy -2.588445
v 5.39765
angle 28.656041
In [ ]:
angle_at_contact_frame_s = df_s.loc[contact_frame_num]["angle"]
angle_at_leave_frame_s = df_s.loc[leave_frame_num]["angle"]

angle_at_contact_frame_c = df_c.loc[contact_frame_num]["angle"]
angle_at_leave_frame_c = df_c.loc[leave_frame_num]["angle"]


if angle_at_contact_frame_s < 0:
    angle_at_contact_frame_s = 180 + angle_at_contact_frame_s

if angle_at_contact_frame_c < 0:
    angle_at_contact_frame_c = 180 + angle_at_contact_frame_c


angle_at_contact_frame_c, angle_at_contact_frame_s, angle_at_leave_frame_c, angle_at_leave_frame_s
Out[ ]:
(88.31531568210372, 89.298416994945, 30.068582821862446, 28.65604087866925)

Speeds¶

In [ ]:
velocity_at_leave_frame_s = df_s.loc[leave_frame_num]["v"]
velocity_at_contact_frame_s = df_s.loc[contact_frame_num]["v"]
velocity_at_leave_frame_s, velocity_at_contact_frame_s
Out[ ]:
(5.397649793125025, 5.2786822041945936)
In [ ]:
velocity_at_leave_frame_c = df_c.loc[leave_frame_num]["v"]
velocity_at_contact_frame_c = df_c.loc[contact_frame_num]["v"]
velocity_at_leave_frame_c, velocity_at_contact_frame_c
Out[ ]:
(6.272713828600043, 4.859243243341414)
In [ ]:
x_velocity_at_leave_frame_s = df_s.loc[leave_frame_num]["vx"]
x_velocity_at_contact_frame_s = df_s.loc[contact_frame_num]["vx"]
y_velocity_at_leave_frame_s = df_s.loc[leave_frame_num]["vy"]
y_velocity_at_contact_frame_s = df_s.loc[contact_frame_num]["vy"]
print(
    x_velocity_at_leave_frame_s,
    x_velocity_at_contact_frame_s,
    y_velocity_at_leave_frame_s,
    y_velocity_at_contact_frame_s,
)

x_velocity_at_leave_frame_c = df_c.loc[leave_frame_num]["vx"]
x_velocity_at_contact_frame_c = df_c.loc[contact_frame_num]["vx"]
y_velocity_at_leave_frame_c = df_c.loc[leave_frame_num]["vy"]
y_velocity_at_contact_frame_c = df_c.loc[contact_frame_num]["vy"]
print(
    x_velocity_at_leave_frame_c,
    x_velocity_at_contact_frame_c,
    y_velocity_at_leave_frame_c,
    y_velocity_at_contact_frame_c,
)
4.736515139237748 -0.06463549685330301 -2.5884450206628378 5.27828647057236
5.428571428571429 -0.14285714285714285 -3.142857142857143 4.857142857142857

Fitting Curves¶

The Curves to be Fitted¶

We'll assume that downward is the positive direction. In this way, the gravitational acceleration is positive. In x direction, no force is acting and hence the equation of motion is simply:

$$ x(t) = x_0 + v_{x0}t $$

Here $x_0$ is the initial x position, $v_{x0}$ is the initial y velocity.

Now, in y direction, the equation of motion is:

$$ y(t) = y_0 + v_{y0}t + \frac{1}{2}gt^2 $$

Here, $y_0$ is the initial y position, $v_{y0}$ is the initial y velocity, and $g$ is the acceleration due to gravity.

We'll optimize these two equations to get the initial velocity and the initial position for x and y direction.

We can also phrase the same problem by eliminating $t$ from the equation of motions. This way, we'll get $y$ as a function of $x$. Eliminating $t$ from the equation of motion, we get:

$$ y = y_0 + \frac{v_y}{v_x}(x - x_0) + \frac{1}{2}g\frac{(x - x_0)^2}{v_x^2} $$

Here, we have rewritten $v_{x0}$ as $v_x$ and $v_{y0}$ as $v_y$.

This is a parabola with the parameters $x_0$, $y_0$, $v_y$, $v_x$ and $g$. We can use scipy to get these parameters. However, as we already know the values of $x_0$ and $y_0$ with reasonable accuracy, we'll use them.

Similarly, fitting the first two equations gives the same parameters.

In [ ]:
def the_parabola_to_fit(x, m, a, x0, y0):
    second_term = (m) * (x - x0)
    third_term = a * ((x - x0) ** 2)
    return y0 + second_term + third_term


def parametric_x_to_fit(t, vx0, x0):
    return x0 + vx0 * t


def parametric_y_to_fit(t, vy0, g, y0):
    return y0 + vy0 * t + 0.5 * g * t**2

Region III¶

Data For Region III¶

In [ ]:
region_3 = df_c[df_c["Region"] == "III"]
In [ ]:
X = region_3["x"].values
x0 = X[0]
Y = region_3["y"].values
y0 = Y[0]
t = region_3["time"].values
offset = t[0]
tbar = t - offset
In [ ]:
x0, y0
Out[ ]:
(969.0, 606.0)
In [ ]:
tbar
Out[ ]:
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
       17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33,
       34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50,
       51, 52], dtype=int64)

Fitting the Curves In Region III¶

In [ ]:
the_parabola = partial(the_parabola_to_fit, x0=x0, y0=y0)
parametric_x = partial(parametric_x_to_fit, x0=x0)
parametric_y = partial(parametric_y_to_fit, y0=y0)
the_parabola_vector = np.vectorize(the_parabola)
parametric_x_vector = np.vectorize(parametric_x)
parametric_y_vector = np.vectorize(parametric_y)
In [ ]:
popt, pcov = curve_fit(the_parabola, X, Y)
popty, pcovy = curve_fit(parametric_y, tbar, Y)
poptx, pcovx = curve_fit(parametric_x, tbar, X)
In [ ]:
popt, popty, poptx
Out[ ]:
(array([-0.52754421,  0.00195145]),
 array([-2.52394612,  0.08890582]),
 array([4.74636119]))

Caparing Results For Region III¶

Using

$$ m = \frac{v_y}{v_x}\\ a = \frac{g}{2v_x^2} $$

we can check whether the parameters by both the equations are the same.

In [ ]:
m_by_parametric = popty[0] / poptx[0]
m_by_parabola = popt[0]
m_by_parametric, m_by_parabola
Out[ ]:
(-0.5317644437316823, -0.5275442095377482)
In [ ]:
a_by_parametric = popty[1] / poptx[0] ** 2 / 2
a_by_parabola = popt[1]
a_by_parametric, a_by_parabola
Out[ ]:
(0.0019732342128660173, 0.0019514472283770265)

Calculating Informations From Parameters In Region III¶

The Speeds In Region III¶

Next, we'll see how the calculated velocities are? The eqaution for the speeds are:

$$ v_x(t) = v_{x0}\\ v_y(t) = v_{y0} + gt $$
In [ ]:
vy = popty[0] + popty[1] * (tbar)
vx = np.ones(len(tbar)) * poptx[0]
v = np.sqrt(vy**2 + vx**2)

The Angle In Region III¶

Next, let's calculate the angle between the x and y velocity.

In [ ]:
angles = np.arctan(vy / vx) * 180 / np.pi

Visualizating Results In Region III¶

x and y Coordinates In Region III¶

In [ ]:
plt.scatter(tbar, X, label="X Data")
title = "X vs Time for Region III"
plt.plot(tbar, parametric_x_vector(tbar, *poptx), "r", label="X Fitted")
plt.legend()
plt.xlabel("Time in ms")
plt.ylabel("X in pixels")
plt.title(title)
save_name = RESULT_DIR + "/" + title.replace(" ", "_") + ".png"
plt.savefig(save_name)
plt.show()
In [ ]:
plt.scatter(tbar, Y, label="y Data")
title = "Y vs Time for Region III"
plt.plot(tbar, parametric_y_vector(tbar, *popty), "r", label="y Fitted")
plt.legend()
plt.xlabel("Time in ms")
plt.ylabel("y in pixels")
plt.title(title)
save_name = RESULT_DIR + "/" + title.replace(" ", "_") + ".png"
plt.savefig(save_name)
plt.show()
In [ ]:
plt.plot(X, Y, "o", label="x vs y Data")
title = "X vs Y for Region III Using Parabola"
plt.plot(X, the_parabola_vector(X, *popt), "r", label="x vs y with Parabola")
plt.legend()
plt.xlabel("x in pixels")
plt.ylabel("y in pixels")
plt.title(title)
save_name = RESULT_DIR + "/" + title.replace(" ", "_") + ".png"
plt.savefig(save_name)
plt.show()
In [ ]:
plt.plot(X, Y, "o", label="x vs y Data")
title = "X vs Y for Region III Using Parametric"
plt.plot(parametric_x_vector(tbar, *poptx), parametric_y_vector(tbar, *popty), "r", label="x vs y with Parametric")
plt.legend()
plt.xlabel("x in pixels")
plt.ylabel("y in pixels")
plt.title(title)
save_name = RESULT_DIR + "/" + title.replace(" ", "_") + ".png"
plt.savefig(save_name)
plt.show()

Speeds In Region III¶

In [ ]:
plt.plot(tbar, region_3["vx"].values, label="$v_x$ Data")
title = "$v_x$ vs Time for Region III"
plt.plot(tbar, vx, "r", label="$v_x$ Calculated")
plt.legend()
plt.xlabel("Time in ms")
plt.ylabel("$v_x$ in pixels/ms")
plt.title(title)
save_name = RESULT_DIR + "/" + title.replace(" ", "_").replace("$", "") + ".png"
plt.savefig(save_name)
plt.show()
In [ ]:
plt.plot(tbar, region_3["vy"].values, label="$v_y$ Data")
title = "$v_y$ vs Time for Region III"
plt.plot(tbar, vy, "r", label="$v_y$ Calculated")
plt.legend()
plt.xlabel("Time in ms")
plt.ylabel("$v_y$ in pixels/ms")
plt.title(title)
save_name = RESULT_DIR + "/" + title.replace(" ", "_").replace("$", "") + ".png"
plt.savefig(save_name)
plt.show()
In [ ]:
plt.plot(tbar, region_3["v"].values, label="$v$ Data")
title = "$v$ vs Time for Region III"
plt.plot(tbar, v, "r", label="$v$ Calculated")
plt.legend()
plt.xlabel("Time in ms")
plt.ylabel("$v$ in pixels/ms")
plt.title(title)
save_name = RESULT_DIR + "/" + title.replace(" ", "_").replace("$", "") + ".png"
plt.savefig(save_name)
plt.show()

Angle In Region III¶

In [ ]:
plt.plot(region_3["angle"].values, label="Angle data")
title = "Angle vs Time for Region III"
plt.plot(-angles, "r", label="Angle calculated")
plt.xlabel("Time in ms")
plt.ylabel("Angle in degrees")
plt.title(title)
save_name = RESULT_DIR + "/" + title.replace(" ", "_") + ".png"
plt.savefig(save_name)
plt.legend()
plt.show()

Getting The Required Informations In Region III¶

In [ ]:
g_raw = popty[1]
vx_using_curve = poptx[0]
vy_using_curve = popty[1]
v_using_curve = np.sqrt(vx_using_curve**2 + vy_using_curve**2)
In [ ]:
fps = 1000
pixels = 0.0115
speed_conversion = pixels * fps
acceleration_conversion = pixels * fps**2
g_in_region_3 = g_raw * acceleration_conversion
g_in_region_3
Out[ ]:
1022.4169495159215
In [ ]:
x_velocity_at_leave_frame_using_c = vx[0]
y_velocity_at_leave_frame_using_c = vy[0]
velocity_at_leave_frame_using_c = v[0]
angle_at_leave_frame_using_c = angles[0]
x_velocity_at_leave_frame_using_c, y_velocity_at_leave_frame_using_c, velocity_at_leave_frame_using_c, angle_at_leave_frame_using_c
Out[ ]:
(4.746361185991997,
 -2.5239461158186822,
 5.375709116335032,
 -28.002457200364926)

Adding the Information for Region III to DataFrame¶

In [ ]:
new_info_df_for_region_3 = pd.DataFrame(
    {"vx": vx, "vy": vy, "v": v, "angle": angles, "time": t}
)
new_info_df_for_region_3.columns = [
    "vx_using_curve",
    "vy_using_curve",
    "v_using_curve",
    "angle_using_curve",
    "time",
]

Region I¶

Data For Region I¶

In [ ]:
region_1 = df_c[df_c["Region"] == "I"]
In [ ]:
X = region_1["x"].values
x0 = X[0]
Y = region_1["y"].values
y0 = Y[0]
t = region_1["time"].values
offset = t[0]
tbar = t - offset
In [ ]:
x0, y0
Out[ ]:
(870.0, 411.0)
In [ ]:
tbar
Out[ ]:
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
       17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33,
       34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50])

Fitting the Curves¶

In [ ]:
the_parabola = partial(the_parabola_to_fit, x0=x0, y0=y0)
parametric_x = partial(parametric_x_to_fit, x0=x0)
parametric_y = partial(parametric_y_to_fit, y0=y0)
the_parabola_vector = np.vectorize(the_parabola)
parametric_x_vector = np.vectorize(parametric_x)
parametric_y_vector = np.vectorize(parametric_y)
In [ ]:
popt, pcov = curve_fit(the_parabola, X, Y)
popty, pcovy = curve_fit(parametric_y, tbar, Y)
poptx, pcovx = curve_fit(parametric_x, tbar, X)
In [ ]:
popt, popty, poptx
Out[ ]:
(array([-32.63023863,   1.64840318]),
 array([1.05835668, 0.08616752]),
 array([-0.06867793]))

Caparing Results¶

Using

$$ m = \frac{v_y}{v_x}\\ a = \frac{g}{2v_x^2} $$

we can check whether the parameters by both the equations are the same.

In [ ]:
m_by_parametric = popty[0] / poptx[0]
m_by_parabola = popt[0]
m_by_parametric, m_by_parabola
Out[ ]:
(-15.410434368564319, -32.630238632389656)
In [ ]:
a_by_parametric = popty[1] / poptx[0] ** 2 / 2
a_by_parabola = popt[1]
a_by_parametric, a_by_parabola
Out[ ]:
(9.134383905042618, 1.6484031817656235)

Calculating Informations From Parameters¶

The Speeds¶

Next, we'll see how the calculated velocities are? The eqaution for the speeds are:

$$ v_x(t) = v_{x0}\\ v_y(t) = v_{y0} + gt $$
In [ ]:
vy = popty[0] + popty[1] * (tbar)
vx = np.ones(len(tbar)) * poptx[0]
v = np.sqrt(vy**2 + vx**2)

The Angle¶

Next, let's calculate the angle between the x and y velocity.

In [ ]:
angles = np.arctan(vy / vx) * 180 / np.pi

Visualizating Results¶

x and y Coordinates¶

In [ ]:
plt.scatter(tbar, X, label="X Data")
title = "X vs Time for Region I"
plt.plot(tbar, parametric_x_vector(tbar, *poptx), "r", label="X Fitted")
plt.legend()
plt.xlabel("Time in ms")
plt.ylabel("X in pixels")
plt.title(title)
save_name = RESULT_DIR + "/" + title.replace(" ", "_") + ".png"
plt.savefig(save_name)
plt.show()
In [ ]:
plt.scatter(tbar, Y, label="y Data")
title = "Y vs Time for Region I"
plt.plot(tbar, parametric_y_vector(tbar, *popty), "r", label="y Fitted")
plt.legend()
plt.xlabel("Time in ms")
plt.ylabel("y in pixels")
plt.title(title)
save_name = RESULT_DIR + "/" + title.replace(" ", "_") + ".png"
plt.savefig(save_name)
plt.show()
In [ ]:
plt.plot(X, Y, "o", label="x vs y Data")
title = "X vs Y for Region I Using Parabola"
plt.plot(X, the_parabola_vector(X, *popt), "r", label="x vs y with Parabola")
plt.legend()
plt.xlabel("x in pixels")
plt.ylabel("y in pixels")
plt.title(title)
save_name = RESULT_DIR + "/" + title.replace(" ", "_") + ".png"
plt.savefig(save_name)
plt.show()
In [ ]:
plt.plot(X, Y, "o", label="x vs y Data")
title = "X vs Y for Region I Using Parametric"
plt.plot(parametric_x_vector(tbar, *poptx), parametric_y_vector(tbar, *popty), "r", label="x vs y with Parametric")
plt.legend()
plt.xlabel("x in pixels")
plt.ylabel("y in pixels")
plt.title(title)
save_name = RESULT_DIR + "/" + title.replace(" ", "_") + ".png"
plt.savefig(save_name)
plt.show()

Speeds¶

In [ ]:
plt.plot(tbar, region_1["vx"].values, label="$v_x$ Data")
title = "$v_x$ vs Time for Region I"
plt.plot(tbar, vx, "r", label="$v_x$ Calculated")
plt.legend()
plt.xlabel("Time in ms")
plt.ylabel("$v_x$ in pixels/ms")
plt.title(title)
save_name = RESULT_DIR + "/" + title.replace(" ", "_").replace("$", "") + ".png"
plt.savefig(save_name)
plt.show()
In [ ]:
plt.plot(tbar, region_1["vy"].values, label="$v_y$ Data")
title = "$v_y$ vs Time for Region I"
plt.plot(tbar, vy, "r", label="$v_y$ Calculated")
plt.legend()
plt.xlabel("Time in ms")
plt.ylabel("$v_y$ in pixels/ms")
plt.title(title)
save_name = RESULT_DIR + "/" + title.replace(" ", "_").replace("$", "") + ".png"
plt.savefig(save_name)
plt.show()
In [ ]:
plt.plot(tbar, region_1["v"].values, label="$v$ Data")
title = "$v$ vs Time for Region I"
plt.plot(tbar, v, "r", label="$v$ Calculated")
plt.legend()
plt.xlabel("Time in ms")
plt.ylabel("$v$ in pixels/ms")
plt.title(title)
save_name = RESULT_DIR + "/" + title.replace(" ", "_").replace("$", "") + ".png"
plt.savefig(save_name)
plt.show()

Angle¶

In [ ]:
plt.plot(region_1["angle"].values, label="Angle data")
title = "Angle vs Time for Region I"
plt.plot(-angles, "r", label="Angle calculated")
plt.xlabel("Time in ms")
plt.ylabel("Angle in degrees")
plt.title(title)
save_name = RESULT_DIR + "/" + title.replace(" ", "_") + ".png"
plt.savefig(save_name)
plt.legend()
plt.show()

Getting The Required Informations¶

In [ ]:
fps = 1000
pixels = 0.0115
speed_conversion = pixels * fps
acceleration_conversion = pixels * fps**2
g_raw = popty[1]
g_in_region_1 = g_raw * acceleration_conversion
g_in_region_1
Out[ ]:
990.9265101122728
In [ ]:
x_velocity_at_contact_frame_using_c = vx[-1]
y_velocity_at_contact_frame_using_c = vy[-1]
velocity_at_contact_frame_using_c = v[-1]
angle_at_contact_frame_using_c = angles[-1]
x_velocity_at_contact_frame_using_c, y_velocity_at_contact_frame_using_c, velocity_at_contact_frame_using_c, angle_at_contact_frame_using_c
Out[ ]:
(-0.06867792661852179,
 5.366732811646731,
 5.3671722283908725,
 -89.2668275651495)
In [ ]:
h_using_c = Y[-1] - Y[0]
h_using_c
Out[ ]:
160.0
In [ ]:
if angle_at_contact_frame_using_c < 0:
    angle_at_contact_frame_using_c = angle_at_contact_frame_using_c + 180
In [ ]:
new_info_df_for_region_1 = pd.DataFrame(
    {"vx": vx, "vy": vy, "v": v, "angle": angles, "time": t}
)
new_info_df_for_region_1.columns = [
    "vx_using_curve",
    "vy_using_curve",
    "v_using_curve",
    "angle_using_curve",
    "time",
]

Adding the Additional Information¶

Saving Informations to DataFrame¶

In [ ]:
info_df = pd.concat([new_info_df_for_region_1, new_info_df_for_region_3], axis=0)
In [ ]:
df_final = pd.merge(df_c, info_df, on="time", how="left")
df_final.head()
Out[ ]:
id x y r1 r2 theta Region time vx vy v angle vx_using_curve vy_using_curve v_using_curve angle_using_curve
0 ../../data/extracted_images/ref/007.jpg 870.0 404.0 11.0 10.0 100.267614 O 7 0.142857 0.142857 0.202031 -45.000000 NaN NaN NaN NaN
1 ../../data/extracted_images/ref/008.jpg 870.0 405.0 11.0 10.0 87.662543 O 8 0.142857 0.285714 0.319438 -63.434949 NaN NaN NaN NaN
2 ../../data/extracted_images/ref/009.jpg 870.0 405.0 11.0 10.0 76.203387 O 9 0.142857 0.285714 0.319438 -63.434949 NaN NaN NaN NaN
3 ../../data/extracted_images/ref/010.jpg 871.0 406.0 10.0 11.0 128.915504 O 10 0.285714 0.428571 0.515079 -56.309932 NaN NaN NaN NaN
4 ../../data/extracted_images/ref/011.jpg 870.0 406.0 11.0 10.0 29.793805 O 11 0.142857 0.428571 0.451754 -71.565051 NaN NaN NaN NaN

The Text Information¶

Creating the Text¶

In [ ]:
pattern = "***"
information = f"""
{pattern*20}
### TOTAL FRAMES: {total_frames}
### NONE FRAMES: {none_frames}
### UNREALISTIC FRAMES: {unrealistic}
### PASSTHROUGH: {passthrough}

{pattern*20}
USING THE SMOOTHENED DATA
AT CONTACT FRAME:
### H: {np.round(hs, 1)}
### ANGLE: {np.round(-90+angle_at_contact_frame_s+float(angle), 2)}
### VELOCITY: {np.round(velocity_at_contact_frame_s, 2)}
### X VELOCITY: {np.round(x_velocity_at_contact_frame_s, 2)}
### Y VELOCITY: {np.round(y_velocity_at_contact_frame_s, 2)}

AT LEAVE FRAME:
### ANGLE: {np.round(angle_at_leave_frame_s, 2)}
### VELOCITY: {np.round(velocity_at_leave_frame_s, 2)}
### X VELOCITY: {np.round(x_velocity_at_leave_frame_s, 2)}
### Y VELOCITY: {np.round(y_velocity_at_leave_frame_s, 2)}

{pattern*20}
USING THE RAW DATA
AT CONTACT FRAME:
### H: {np.round(hc, 1)}
### ANGLE: {np.round(-90+angle_at_contact_frame_c+float(angle), 2)}
### VELOCITY: {np.round(velocity_at_contact_frame_c, 2)}
### X VELOCITY: {np.round(x_velocity_at_contact_frame_c, 2)}
### Y VELOCITY: {np.round(y_velocity_at_contact_frame_c, 2)}

AT LEAVE FRAME:
### ANGLE: {np.round(angle_at_leave_frame_c, 2)}
### VELOCITY: {np.round(velocity_at_leave_frame_c, 2)}
### X VELOCITY: {np.round(x_velocity_at_leave_frame_c, 2)}
### Y VELOCITY: {np.round(y_velocity_at_leave_frame_c, 2)}

{pattern*20}
USING CURVE FITTING
AT CONTACT FRAME:
### H: {np.round(h_using_c, 1)}
### ANGLE: {np.round(-90+angle_at_contact_frame_using_c+float(angle), 2)}
### VELOCITY: {np.round(velocity_at_contact_frame_using_c, 2)}
### X VELOCITY: {np.round(x_velocity_at_contact_frame_using_c, 2)}
### Y VELOCITY: {np.round(y_velocity_at_contact_frame_using_c, 2)}
### g: {np.round(g_in_region_1, 2)}

AT LEAVE FRAME:
### ANGLE: {np.round(-angle_at_leave_frame_using_c, 2)}
### VELOCITY: {np.round(velocity_at_leave_frame_using_c, 2)}
### X VELOCITY: {np.round(x_velocity_at_leave_frame_using_c, 2)}
### Y VELOCITY: {np.round(y_velocity_at_leave_frame_using_c, 2)}
### g: {np.round(g_in_region_3, 2)}
"""
print(information)
************************************************************
### TOTAL FRAMES: 171
### NONE FRAMES: 3
### UNREALISTIC FRAMES: 3
### PASSTHROUGH: 0

************************************************************
USING THE SMOOTHENED DATA
AT CONTACT FRAME:
### H: 164.3
### ANGLE: 23.8
### VELOCITY: 5.28
### X VELOCITY: -0.06
### Y VELOCITY: 5.28

AT LEAVE FRAME:
### ANGLE: 28.66
### VELOCITY: 5.4
### X VELOCITY: 4.74
### Y VELOCITY: -2.59

************************************************************
USING THE RAW DATA
AT CONTACT FRAME:
### H: 161.0
### ANGLE: 22.82
### VELOCITY: 4.86
### X VELOCITY: -0.14
### Y VELOCITY: 4.86

AT LEAVE FRAME:
### ANGLE: 30.07
### VELOCITY: 6.27
### X VELOCITY: 5.43
### Y VELOCITY: -3.14

************************************************************
USING CURVE FITTING
AT CONTACT FRAME:
### H: 160.0
### ANGLE: 25.23
### VELOCITY: 5.37
### X VELOCITY: -0.07
### Y VELOCITY: 5.37
### g: 990.93

AT LEAVE FRAME:
### ANGLE: 28.0
### VELOCITY: 5.38
### X VELOCITY: 4.75
### Y VELOCITY: -2.52
### g: 1022.42

First, create a new string containing just the previous text file. Else we'll duplicate the text file.

In [ ]:
with open(RESULT_DIR + "/info.txt", "r+") as f:
    texts = f.readlines()
    text = "".join(texts[:6])
print(text[:125])
all_text = text + information
### ref.tif
### First Frame ID: 017
### Last Frame ID: 161
### Contact Frame ID: 068
### Leave Frame ID: 107
### Angle: 24.5

In [ ]:
with open(RESULT_DIR + "/info.txt", "w") as f:
    f.writelines(all_text)

Save the DataFrames¶

In [ ]:
df_final.to_csv(RESULT_DIR + f"/{sequence}_final.csv", index=False)
df_s.to_csv(RESULT_DIR + f"/{sequence}_smoothened.csv", index=False)
df_c.to_csv(RESULT_DIR + f"/{sequence}_raw.csv", index=False)